<template>
  <div class="review-system-container">
    <!-- 顶部导航栏 -->
    <header class="top-nav">
      <div class="logo-title">
        <h1>吉林油田公司科学技术奖网评系统</h1>
      </div>
      <div class="user-info-container">
        <!-- 评审时间显示 -->
        <div class="review-time-info" v-if="reviewStartTime && reviewEndTime">
          <i class="el-icon-clock"></i>
          <span class="time-text">评审时间：{{ formatReviewTime() }}</span>
        </div>

        <el-dropdown @command="handleUserCommand">
            <span class="user-info">
              <i class="el-icon-user-circle"></i>
              <span class="username">{{ currentUser.name }}</span>
              <span class="specialty-tag">{{ currentUser.specialty }}</span>
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="logout" divided>
              <i class="el-icon-switch-button"></i> 退出登录
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </header>

    <!-- 筛选和排序区 -->
    <div class="filter-sort-bar">
      <div class="filter-group">
        <!-- 评审状态筛选 -->
        <el-select
            v-model="filterStatus"
            placeholder="评审状态"
            style="width: 160px; margin-right: 15px;"
            @change="handleFilterChange"
        >
          <el-option label="全部项目" value="all"></el-option>
          <el-option label="未评审" value="unreviewed"></el-option>
          <el-option label="评审中" value="inreview"></el-option>
          <el-option label="已评审" value="reviewed"></el-option>
          <el-option label="已提交" value="submitted"></el-option>
        </el-select>

        <!-- 项目搜索 -->
        <el-input
            v-model="searchKeyword"
            placeholder="搜索项目名称..."
            prefix-icon="el-icon-search"
            style="width: 300px;"
            @input="handleSearch"
        ></el-input>
      </div>

      <!-- 排序控制 -->
      <div class="sort-group">
        <el-select
            v-model="sortType"
            placeholder="排序方式"
            style="width: 200px;"
            @change="handleSortChange"
        >
          <el-option label="默认顺序" value="default"></el-option>
          <el-option label="申报等级（高→低）" value="level_desc"></el-option>
          <el-option label="申报等级（低→高）" value="level_asc"></el-option>
          <el-option label="评审分数（高→低）" value="score_desc" v-if="hasReviewedProjects"></el-option>
          <el-option label="评审分数（低→高）" value="score_asc" v-if="hasReviewedProjects"></el-option>
        </el-select>
      </div>
    </div>

    <!-- 评审进度概览 -->
    <div class="review-progress">
      <div class="progress-info">
        <span>评审进度：</span>
        <span class="completed-count">{{ completedReviewCount }}</span>
        <span>/</span>
        <span class="total-count">{{ filteredProjects.length }}</span>
        <span>个项目</span>
      </div>
      <el-progress
          :percentage="reviewProgressPercentage"
          :stroke-width=6
          :status="isAllSubmitted ? 'success' : undefined"
          style="flex: 1; margin: 0 15px;"
      ></el-progress>
      <el-button
          type="primary"
          icon="el-icon-check"
          @click="submitAllReviews"
          :disabled="!canSubmitAll || isAllSubmitted"
          :loading="submitLoading"
      >
        全部提交
      </el-button>
    </div>

    <!-- 项目列表 -->
    <div class="project-list-container">
      <el-table
          :data="filteredProjects"
          border
          style="width: 100%;"
          :row-class-name="tableRowClassName"
          :highlight-current-row="true"
      >
        <el-table-column
            type="index"
            label="序号"
            width="60">
        </el-table-column>
        <el-table-column
            prop="projectName"
            label="项目名称"
            min-width="300">
        </el-table-column>
        <el-table-column
            prop="declareLevel"
            label="申报等级">
          <template slot-scope="scope">
            <el-tag :type="getLevelTagType(scope.row.declareLevel)">
              {{ scope.row.declareLevel }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- 业务需求得分 -->
        <el-table-column
            prop="bgScore"
            label="业务需求得分">
          <template slot-scope="scope">
            <div
                class="score-cell"
                @click="openScoreDrawer(scope.row, 'bg')"
                :class="{ 'disabled-score': scope.row.scoreStatus === 3 }"
            >
              <span v-if="scope.row.bgScore !== null" class="reviewed-score">{{ scope.row.bgScore }}</span>
              <span v-else class="unreviewed-score">-</span>
              <i class="el-icon-edit-outline score-edit-icon"></i>
            </div>
          </template>
        </el-table-column>
        <!-- 创造性得分 -->
        <el-table-column
            prop="innovationScore"
            label="创造性得分">
          <template slot-scope="scope">
            <div
                class="score-cell"
                @click="openScoreDrawer(scope.row, 'innovation')"
                :class="{ 'disabled-score': scope.row.scoreStatus === 3 }"
            >
                <span v-if="scope.row.innovationScore !== null" class="reviewed-score">{{
                    scope.row.innovationScore
                  }}</span>
              <span v-else class="unreviewed-score">-</span>
              <i class="el-icon-edit-outline score-edit-icon"></i>
            </div>
          </template>
        </el-table-column>
        <!-- 效益性得分 -->
        <el-table-column
            prop="economicScore"
            label="效益性得分">
          <template slot-scope="scope">
            <div
                class="score-cell"
                @click="openScoreDrawer(scope.row, 'economic')"
                :class="{ 'disabled-score': scope.row.scoreStatus === 3 }"
            >
                <span v-if="scope.row.economicScore !== null" class="reviewed-score">{{
                    scope.row.economicScore
                  }}</span>
              <span v-else class="unreviewed-score">-</span>
              <i class="el-icon-edit-outline score-edit-icon"></i>
            </div>
          </template>
        </el-table-column>
        <el-table-column
            prop="totalScore"
            label="总分"
            width="120">
          <template slot-scope="scope">
            <span v-if="scope.row.totalScore !== '-'" class="reviewed-score">{{ scope.row.totalScore }}</span>
            <span v-else class="unreviewed-score">-</span>
          </template>
        </el-table-column>
        <el-table-column
            prop="status"
            label="评审状态">
          <template slot-scope="scope">
            <el-tag :type="getScoreStatusTagType(scope.row.scoreStatus)">
              <i :class="getScoreStatusIcon(scope.row.scoreStatus)"></i>
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态提示 -->
      <div v-if="filteredProjects.length === 0" class="empty-state">
        <el-empty
            description="当前没有符合条件的项目"
        ></el-empty>
      </div>
    </div>

    <!-- 页脚信息 -->
    <div class="review-footer">
      <p>© 2025 吉林油田公司科学技术奖网评系统 版权所有</p>
      <p>技术支持：地球物理勘探研究院</p>
    </div>

    <!-- 打分抽屉 -->
    <el-drawer
        v-if="currentProject"
        :title="scoreDialogTitle"
        :visible.sync="scoreDrawerVisible"
        size="60%"
        direction="rtl"
        :modal="true"
        @close="handleDrawerClose"
        :before-close="handleDrawerBeforeClose"
    >
      <div>
        <el-form
            ref="scoreForm"
            :model="reviewForm"
            label-width="120px"
            class="score-form"
        >
          <!-- 项目名称 -->
          <el-form-item label="项目名称">
            <el-input
                v-model="currentProject.projectName"
                readonly
                :disabled="true"
            ></el-input>
          </el-form-item>

          <!-- 内容展示 -->
          <el-form-item :label="contentLabel">
            <el-card>
              <div class="collapsible-content">
                <p class="preformatted-text">
                  {{ currentContent }}
                </p>
              </div>
            </el-card>
          </el-form-item>

          <!-- 评分标准 -->
          <el-form-item label="评分标准">
            <el-card class="criteria-card">
              <div class="toggle-button criteria-toggle" @click="criteriaCollapsed = !criteriaCollapsed">
                <span>{{ criteriaCollapsed ? '查看评分标准' : '收起评分标准' }}</span>
                <i :class="criteriaCollapsed ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"></i>
              </div>
              <div v-if="!criteriaCollapsed" class="criteria-table-wrapper">
                <table class="criteria-table">
                  <thead>
                  <tr>
                    <th style="text-align: center">分数范围</th>
                    <th style="text-align: center">评分标准</th>
                  </tr>
                  </thead>
                  <tbody>
                  <!-- 评分标准内容 -->
                  <template v-if="scoreType === 'bg'">
                    <tr>
                      <td>16~20分</td>
                      <td>
                        成果直接支撑公司主营业务发展，显著提升业务竞争力，或对未来新兴业务具有极强的引领作用，预期将带来重大业务变革。
                      </td>
                    </tr>
                    <tr>
                      <td>11~15分</td>
                      <td>成果对公司主营业务发展有重要支持作用，或对未来新兴业务有显著推动作用。</td>
                    </tr>
                    <tr>
                      <td>6~10分</td>
                      <td>成果对公司业务有一定支持作用，但影响相对有限。</td>
                    </tr>
                    <tr>
                      <td>0~5分</td>
                      <td>成果对公司业务影响较小，或尚未体现明显支持作用。</td>
                    </tr>
                  </template>
                  <template v-if="scoreType === 'innovation'">
                    <tr>
                      <td>36~40分</td>
                      <td>
                        在关键技术或者系统集成上有特别重大创新或突破，技术难度大。总体技术和主要技术经济指标达到或超过集团公司内部技术或产品的领先水平。
                      </td>
                    </tr>
                    <tr>
                      <td>31~35分</td>
                      <td>
                        在关键技术或者系统集成上有重大创新或突破，技术难度较大。总体技术和主要技术经济指标达到或超过集团公司内部技术或产品的先进水平。
                      </td>
                    </tr>
                    <tr>
                      <td>26~30分</td>
                      <td>
                        在关键技术或者系统集成上有较大创新或突破，技术难度适中。总体技术和主要技术经济指标达到或超过公司技术或产品的领先水平。
                      </td>
                    </tr>
                    <tr>
                      <td>0~25分</td>
                      <td>
                        在关键技术或者系统集成上有创新或突破，技术获取与技术开发有一定难度。总体技术和主要技术经济指标达到或超过公司技术或产品的先进水平。
                      </td>
                    </tr>
                  </template>
                  <template v-if="scoreType === 'economic'">
                    <tr>
                      <td>36~40分</td>
                      <td>
                        技术成熟度高，市场需求旺盛，推广应用空间大。技术成果实现了显著的效益性，对产业发展、市场增长或企业盈利产生了重大正面影响。
                      </td>
                    </tr>
                    <tr>
                      <td>31~35分</td>
                      <td>
                        技术成熟度较好，市场需求较大，推广应用潜力较好。技术成果带来了良好的效益性，对产业或企业具有实质性的贡献。
                      </td>
                    </tr>
                    <tr>
                      <td>26~30分</td>
                      <td>技术成熟、市场需求和推广应用潜力一般。技术成果具有一定的效益性，但影响相对有限。</td>
                    </tr>
                    <tr>
                      <td>0~25分</td>
                      <td>技术成熟、市场需求和推广应用潜力低。技术成果的效益性不明显，或尚未实现预期的效益性。</td>
                    </tr>
                  </template>
                  </tbody>
                </table>
              </div>
            </el-card>
          </el-form-item>

          <!-- 评分输入 -->
          <el-form-item :label="scoreLabel">
            <el-input-number
                v-model="currentScore"
                :min="0"
                :max="scoreMax"
                :step="1"
                :precision="0"
                @change="calculateTotalScore"
                :disabled="currentProject.scoreStatus === 3"
                class="score-input"
                style="width: 200px"
            ></el-input-number>
            <el-tag style="margin-left: 5px"> 满分：{{ scoreMax }}</el-tag>
          </el-form-item>
        </el-form>

        <!-- 底部按钮组 - 调整布局为靠右 -->
        <div class="drawer-footer">
          <!-- 三个按钮靠右显示 -->
          <div class="button-group">
            <el-button
                v-if="scoreType !== 'bg'"
                @click="handleGoToPrevious"
                type="success"
                :disabled="currentProject.scoreStatus === 3"
                class="prev-btn"
            >
              <i class="el-icon-arrow-left"></i>
              {{ getScoreTypeName(getPreviousScoreType()) }}
            </el-button>

            <el-button
                type="primary"
                @click="handleCloseAndSave"
                :disabled="!canSaveCurrentScore || currentProject.scoreStatus === 3"
                class="close-btn"
            >
              <i class="el-icon-check"></i> 关闭
            </el-button>

            <el-button
                v-if="scoreType !== 'economic'"
                type="success"
                @click="handleGoToNext"
                :disabled="currentProject.scoreStatus === 3"
                class="next-btn"
            >
              {{ getScoreTypeName(getNextScoreType()) }}
              <i class="el-icon-arrow-right"></i>
            </el-button>
          </div>
        </div>
      </div>
    </el-drawer>

    <!-- 全部提交确认弹窗 -->
    <el-dialog
        title="确认提交全部评审结果"
        :visible.sync="submitAllDialogVisible"
        width="400px"
        top="10%"
    >
      <div class="submit-confirm-content">
        <p>您已完成所有{{ filteredProjects.length }}个项目的评审工作。</p>
        <p>提交后，您的评委编码将失效，将无法再次登录系统，请确认是否提交？</p>
        <div class="review-summary">
          <div class="summary-item">
            <span>平均分：</span>
            <span class="summary-value">{{ averageScore.toFixed(1) }}</span>
          </div>
          <div class="summary-item">
            <span>最高分：</span>
            <span class="summary-value">{{ maxScore }}</span>
          </div>
          <div class="summary-item">
            <span>最低分：</span>
            <span class="summary-value">{{ minScore }}</span>
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="submitAllDialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="confirmSubmitAll"
            :loading="submitLoading"
        >
          确认提交
        </el-button>
      </div>
    </el-dialog>

    <!-- 登录后公告弹窗 -->
    <el-dialog
        title="系统公告"
        :visible.sync="announcementVisible"
        width="600px"
        :modal="true"
        :close-on-click-modal="false"
        :show-close="false"
    >
      <div class="announcement-content">
        <h3 style="margin-top: 0;">一、评审时间</h3>
        <p>{{ formatReviewTime() }}</p>

        <h3>二、评审要求</h3>
        <ol class="announcement-list">
          <li>完整性：请对"待评项目"列表中分配给您的全部项目进行逐项评分，确保无一遗漏。</li>
          <li>
            修改规则：在评审期内且未点击"全部提交"前，可多次登录系统修改或调整评分，系统将自动保存最新结果。点击"全部提交"后，评审结果立即锁定，评审账号同步失效，无法再登录或修改。
          </li>
          <li>提交截止：请务必于 {{ formatDate(new Date(reviewEndTime)) }}
            前完成并点击"全部提交"，逾期系统将自动关闭，未提交项目视为无效评审。
          </li>
        </ol>

        <h3>三、重要提醒</h3>
        <ol class="announcement-list" start="4">
          <li>为保证评审公平公正，系统全程记录 IP 地址、MAC 地址及操作日志。</li>
          <li>建议使用最新版Chrome、Edge浏览器，勿使用IE或兼容模式。</li>
          <li>评审前请关闭 VPN、代理及远程控制软件，确保网络环境稳定。</li>
        </ol>

        <p style="margin-top: 20px; color: #1890ff;">感谢各位专家的辛勤付出！</p>
      </div>
      <div slot="footer">
        <el-button
            type="primary"
            @click="announcementVisible = false"
        >
          已阅
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {saveJudge} from '@/api/judge'
import {getProjectScoreList, saveScore, batchSaveScores} from '@/api/score'

export default {
  name: 'Review',
  data() {
    return {
      // 登录相关状态
      currentUser: {
        name: '',
        expertId: null,
        specialty: '',
        id: null
      },
      // 评审时间参数
      reviewStartTime: '',
      reviewEndTime: '',
      // 登录后公告 - 控制弹窗显示
      announcementVisible: false,

      // 项目数据
      allProjects: [],
      filteredProjects: [],

      // 筛选和排序
      filterStatus: 'all',
      searchKeyword: '',
      sortType: 'default',

      // 评审相关 - 打分抽屉
      scoreDrawerVisible: false,
      scoreDialogTitle: '',
      currentProject: null,
      currentProjectIndex: -1, // 当前项目在筛选列表中的索引
      scoreType: '', // 'bg', 'innovation', 'economic'
      currentScore: 0,
      originalScore: 0, // 保存初始分数用于判断是否有修改
      currentContent: '',
      contentLabel: '',
      scoreLabel: '',
      scoreMax: 0,
      criteriaCollapsed: true,
      reviewForm: {
        awardId: null,
        expertId: null,
        bgScore: '',
        innovationScore: '',
        economicScore: '',
        totalScore: '',
        scoreRemark: '',
        scoreStatus: 0 // 默认为未评审状态
      },

      // 全部提交相关
      submitAllDialogVisible: false,
      submitLoading: false
    };
  },

  computed: {
    // 时间警告信息
    showTimeWarning() {
      if (!this.reviewStartTime || !this.reviewEndTime) return false;

      const now = new Date();
      const start = new Date(this.reviewStartTime);
      const end = new Date(this.reviewEndTime);

      return now < start || now > end;
    },

    timeWarningMessage() {
      if (!this.reviewStartTime || !this.reviewEndTime) return '';

      const now = new Date();
      const start = new Date(this.reviewStartTime);
      const end = new Date(this.reviewEndTime);

      if (now < start) {
        return `评审尚未开始，开始时间：${this.formatDate(start)}`;
      } else if (now > end) {
        return `评审已结束，结束时间：${this.formatDate(end)}`;
      }
      return '';
    },
    // 计算已完成评审(已评审+已提交)的项目数量
    completedReviewCount() {
      return this.filteredProjects.filter(project =>
          project.scoreStatus === 2 || project.scoreStatus === 3
      ).length;
    },
    reviewProgressPercentage() {
      if (this.filteredProjects.length === 0) return 0;
      return Math.round((this.completedReviewCount / this.filteredProjects.length) * 100);
    },
    // 判断是否所有项目都已进入已评审或已提交状态
    canSubmitAll() {
      return this.filteredProjects.length > 0 &&
          this.filteredProjects.every(project =>
              project.scoreStatus === 2 || project.scoreStatus === 3
          );
    },
    // 判断是否所有项目都已提交
    isAllSubmitted() {
      return this.filteredProjects.length > 0 &&
          this.filteredProjects.every(project => project.scoreStatus === 3);
    },
    hasReviewedProjects() {
      return this.filteredProjects.some(project =>
          project.scoreStatus === 2 || project.scoreStatus === 3
      );
    },
    averageScore() {
      const reviewedProjects = this.filteredProjects.filter(p =>
          p.scoreStatus === 2 || p.scoreStatus === 3 && p.totalScore !== '-'
      );
      if (reviewedProjects.length === 0) return 0;
      const total = reviewedProjects.reduce((sum, project) => sum + parseFloat(project.totalScore), 0);
      return total / reviewedProjects.length;
    },
    maxScore() {
      const reviewedProjects = this.filteredProjects.filter(p =>
          p.scoreStatus === 2 || p.scoreStatus === 3 && p.totalScore !== '-'
      );
      if (reviewedProjects.length === 0) return 0;
      return Math.max(...reviewedProjects.map(p => parseFloat(p.totalScore)));
    },
    minScore() {
      const reviewedProjects = this.filteredProjects.filter(p =>
          p.scoreStatus === 2 || p.scoreStatus === 3 && p.totalScore !== '-'
      );
      if (reviewedProjects.length === 0) return 0;
      return Math.min(...reviewedProjects.map(p => parseFloat(p.totalScore)));
    },
    canSaveCurrentScore() {
      return this.currentScore >= 0 && this.currentScore <= this.scoreMax;
    },
    // 判断分数是否有变化
    hasScoreChanged() {
      return this.currentScore !== this.originalScore;
    }
  },

  created() {
    // 检查登录状态，如果未登录则跳转到登录页面
    this.checkLoginStatus();
    // 从路由参数获取评审时间
    this.getReviewTimeFromRoute();
  },

  methods: {
    // 从路由参数获取评审时间
    getReviewTimeFromRoute() {
      this.reviewStartTime = this.$route.query.startTime || '';
      this.reviewEndTime = this.$route.query.endTime || '';

      // 如果路由参数中没有，从localStorage获取备份
      if (!this.reviewStartTime || !this.reviewEndTime) {
        const userInfo = JSON.parse(localStorage.getItem('currentUser') || '{}');
        if (userInfo.reviewStartTime && userInfo.reviewEndTime) {
          this.reviewStartTime = userInfo.reviewStartTime;
          this.reviewEndTime = userInfo.reviewEndTime;
        } else {
          console.warn('未获取到评审时间范围信息');
        }
      }
    },

    // 格式化评审时间显示
    formatReviewTime() {
      if (!this.reviewStartTime || !this.reviewEndTime) return '';

      return `${this.formatDate(new Date(this.reviewStartTime))} 起 — ${this.formatDate(new Date(this.reviewEndTime))} 止`;
    },

    // 通用日期格式化
    formatDate(date) {
      if (!(date instanceof Date) || isNaN(date.getTime())) return '';

      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');

      return `${year}年${month}月${day}日 ${hours}:${minutes}`;
    },
    // 检查登录状态和有效期
    checkLoginStatus() {
      const savedUser = localStorage.getItem('currentUser');
      const loginTime = localStorage.getItem('loginTimestamp');
      const hasSeenAnnouncement = localStorage.getItem('hasSeenAnnouncement');

      if (!savedUser || !loginTime) {
        // 未登录或登录信息不完整，跳转到登录页面
        this.redirectToLogin();
        return;
      }

      // 检查登录是否过期（超过1天）
      const now = new Date().getTime();
      if (now - parseInt(loginTime) > 86400000) {
        this.$message.warning('登录已过期，请重新登录');
        this.clearLoginInfo();
        this.redirectToLogin();
        return;
      }

      // 登录有效，加载用户信息
      try {
        this.currentUser = JSON.parse(savedUser);
        this.fetchProjectList().then(() => {
          // 检查是否是首次登录或未查看过公告
          if (!hasSeenAnnouncement) {
            this.announcementVisible = true;
          }
        });
      } catch (error) {
        console.error('解析保存的用户信息失败', error);
        this.clearLoginInfo();
        this.redirectToLogin();
      }
    },

    // 跳转到登录页面
    redirectToLogin() {
      this.$router.push('/auth');
    },

    // 清除登录信息
    clearLoginInfo() {
      localStorage.removeItem('currentUser');
      localStorage.removeItem('hasSeenAnnouncement');
      localStorage.removeItem('loginTimestamp');
      this.currentUser = {name: '', expertId: null, specialty: '', id: null};
    },

    handleUserCommand(command) {
      if (command === 'logout') {
        try {
          this.$confirm('确定要退出登录吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.clearLoginInfo();
            this.redirectToLogin();
            this.$message.success('已退出登录');
          }).catch(() => {
            console.log('用户取消退出登录');
          });
        } catch (error) {
          console.error('退出登录对话框异常', error);
        }
      }
    },

    // 获取项目列表
    async fetchProjectList() {
      try {
        const response = await getProjectScoreList({
          expertId: this.currentUser.expertId,
          specialty: this.currentUser.specialty
        });
        if (response.code === '200') {
          this.allProjects = response.data.map(project => {
            // 计算总分 - 只有三个得分都有值时才计算
            let totalScore = '-';
            let statusText = '';

            // 根据状态码设置状态文本
            switch (project.scoreStatus) {
              case 0:
                statusText = '未评审';
                break;
              case 1:
                statusText = '评审中';
                break;
              case 2:
                statusText = '已评审';
                break;
              case 3:
                statusText = '已提交';
                break;
              default:
                statusText = '未知状态';
            }

            // 只有在已评审或已提交状态下，且三个分数都有值时才计算总分
            if ((project.scoreStatus === 2 || project.scoreStatus === 3) &&
                project.bgScore !== null && project.bgScore !== '' &&
                project.innovationScore !== null && project.innovationScore !== '' &&
                project.economicScore !== null && project.economicScore !== '') {
              totalScore = (
                  parseFloat(project.bgScore) +
                  parseFloat(project.innovationScore) +
                  parseFloat(project.economicScore)
              ).toFixed(1);
            }

            // 处理未填写的分数显示为"-"
            return {
              ...project,
              bgScore: project.bgScore === null || project.bgScore === '' ? '-' : project.bgScore,
              innovationScore: project.innovationScore === null || project.innovationScore === '' ? '-' : project.innovationScore,
              economicScore: project.economicScore === null || project.economicScore === '' ? '-' : project.economicScore,
              totalScore,
              status: statusText
            };
          });
          this.filterProjects();
        } else {
          this.$message.error(response.message || '获取项目列表失败');
        }
      } catch (error) {
        console.error('获取项目列表失败', error);
        this.$message.error('获取项目列表失败，请重试');
      }
    },

    // 项目筛选和排序
    filterProjects() {
      if (!this.currentUser.specialty) return;

      let result = [...this.allProjects];

      // 状态筛选
      if (this.filterStatus === 'unreviewed') {
        result = result.filter(project => project.scoreStatus === 0);
      } else if (this.filterStatus === 'inreview') {
        result = result.filter(project => project.scoreStatus === 1);
      } else if (this.filterStatus === 'reviewed') {
        result = result.filter(project => project.scoreStatus === 2);
      } else if (this.filterStatus === 'submitted') {
        result = result.filter(project => project.scoreStatus === 3);
      }

      // 搜索筛选
      if (this.searchKeyword) {
        const keyword = this.searchKeyword.toLowerCase();
        result = result.filter(project =>
            project.projectName.toLowerCase().includes(keyword)
        );
      }

      this.filteredProjects = this.sortProjects(result);
    },

    sortProjects(projects) {
      const sortedProjects = [...projects];
      const levelWeight = {'一等奖': 3, '二等奖': 2, '三等奖': 1};

      switch (this.sortType) {
        case 'level_desc':
          return sortedProjects.sort((a, b) =>
              levelWeight[b.declareLevel] - levelWeight[a.declareLevel] || a.awardId - b.awardId
          );
        case 'level_asc':
          return sortedProjects.sort((a, b) =>
              levelWeight[a.declareLevel] - levelWeight[b.declareLevel] || a.awardId - b.awardId
          );
        case 'score_desc':
          return sortedProjects.sort((a, b) => {
            if ((a.scoreStatus === 2 || a.scoreStatus === 3) &&
                (b.scoreStatus === 2 || b.scoreStatus === 3) &&
                a.totalScore !== '-' && b.totalScore !== '-') {
              return parseFloat(b.totalScore) - parseFloat(a.totalScore) || a.awardId - b.awardId;
            }
            if (a.scoreStatus === 2 || a.scoreStatus === 3 && a.totalScore !== '-') return -1;
            if (b.scoreStatus === 2 || b.scoreStatus === 3 && b.totalScore !== '-') return 1;
            return a.awardId - b.awardId;
          });
        case 'score_asc':
          return sortedProjects.sort((a, b) => {
            if ((a.scoreStatus === 2 || a.scoreStatus === 3) &&
                (b.scoreStatus === 2 || b.scoreStatus === 3) &&
                a.totalScore !== '-' && b.totalScore !== '-') {
              return parseFloat(a.totalScore) - parseFloat(b.totalScore) || a.awardId - b.awardId;
            }
            if (a.scoreStatus === 2 || a.scoreStatus === 3 && a.totalScore !== '-') return -1;
            if (b.scoreStatus === 2 || b.scoreStatus === 3 && b.totalScore !== '-') return 1;
            return a.awardId - b.awardId;
          });
        default:
          return sortedProjects.sort((a, b) => a.awardId - b.awardId);
      }
    },

    handleFilterChange() {
      this.filterProjects();
    },
    handleSearch() {
      this.filterProjects();
    },
    handleSortChange() {
      this.filterProjects();
    },

    tableRowClassName({row}) {
      if (row.scoreStatus === 3) return 'submitted-row';  // 已提交
      if (row.scoreStatus === 2) return 'reviewed-row';   // 已评审
      if (row.scoreStatus === 1) return 'inreview-row';   // 评审中
      return '';
    },

    getLevelTagType(level) {
      switch (level) {
        case '一等奖':
          return 'primary';
        case '二等奖':
          return 'success';
        case '三等奖':
          return 'info';
        default:
          return 'default';
      }
    },

    // 获取评分状态标签类型
    getScoreStatusTagType(status) {
      switch (status) {
        case 0:
          return 'warning';  // 未评审
        case 1:
          return 'info';     // 评审中
        case 2:
          return 'primary';  // 已评审
        case 3:
          return 'success';  // 已提交
        default:
          return 'default';
      }
    },

    // 获取评分状态图标
    getScoreStatusIcon(status) {
      switch (status) {
        case 0:
          return 'el-icon-time';        // 未评审
        case 1:
          return 'el-icon-edit';        // 评审中
        case 2:
          return 'el-icon-check';       // 已评审
        case 3:
          return 'el-icon-check-circle';// 已提交
        default:
          return 'el-icon-question';
      }
    },

    // 打开打分抽屉
    openScoreDrawer(project, type) {
      // 验证project是否有效
      if (!project || !project.awardId) {
        this.$message.error('项目信息无效，无法打开评审窗口');
        return;
      }

      // 已提交的项目不允许修改
      if (project.scoreStatus === 3) {
        this.$message.warning('该项目已提交，无法修改评分');
        return;
      }

      // 记录当前项目在筛选列表中的索引
      this.currentProjectIndex = this.filteredProjects.findIndex(p => p.awardId === project.awardId);

      // 深拷贝项目对象，避免直接修改原数据
      this.currentProject = JSON.parse(JSON.stringify(project));
      this.scoreType = type;

      // 根据不同类型设置抽屉内容
      this.updateScoreDrawerContent();

      // 显示抽屉
      this.scoreDrawerVisible = true;
    },

    // 更新打分抽屉内容
    updateScoreDrawerContent() {
      switch (this.scoreType) {
        case 'bg':
          this.scoreDialogTitle = '业务需求评分';
          this.contentLabel = '业务需求详情';
          this.currentContent = this.currentProject.projectBg || '无相关信息';
          this.scoreLabel = '业务需求得分';
          this.scoreMax = 20;
          this.currentScore = this.currentProject.bgScore !== null && this.currentProject.bgScore !== '-' ? parseFloat(this.currentProject.bgScore) : 0;
          break;
        case 'innovation':
          this.scoreDialogTitle = '创造性评分';
          this.contentLabel = '创新性详情';
          this.currentContent = this.currentProject.innovation || '无相关信息';
          this.scoreLabel = '创造性得分';
          this.scoreMax = 40;
          this.currentScore = this.currentProject.innovationScore !== null && this.currentProject.innovationScore !== '-' ? parseFloat(this.currentProject.innovationScore) : 0;
          break;
        case 'economic':
          this.scoreDialogTitle = '效益性评分';
          this.contentLabel = '效益性详情';
          this.currentContent = this.currentProject.economicBenefit || '无相关信息';
          this.scoreLabel = '效益性得分';
          this.scoreMax = 40;
          this.currentScore = this.currentProject.economicScore !== null && this.currentProject.economicScore !== '-' ? parseFloat(this.currentProject.economicScore) : 0;
          break;
      }

      // 保存原始分数用于判断是否有修改
      this.originalScore = this.currentScore;

      // 初始化评审表单
      this.reviewForm = {
        awardId: this.currentProject.awardId,
        expertId: this.currentProject.expertId,
        bgScore: this.currentProject.bgScore !== null && this.currentProject.bgScore !== '-' ? parseFloat(this.currentProject.bgScore) : null,
        innovationScore: this.currentProject.innovationScore !== null && this.currentProject.innovationScore !== '-' ? parseFloat(this.currentProject.innovationScore) : null,
        economicScore: this.currentProject.economicScore !== null && this.currentProject.economicScore !== '-' ? parseFloat(this.currentProject.economicScore) : null,
        totalScore: this.currentProject.totalScore !== '-' ? parseFloat(this.currentProject.totalScore) : 0,
        scoreRemark: this.currentProject.scoreRemark || '',
        scoreStatus: this.currentProject.scoreStatus || 0
      };
    },

    // 关闭打分抽屉
    closeScoreDrawer() {
      this.scoreDrawerVisible = false;
      this.currentProject = null;
      this.scoreType = '';
      this.currentScore = 0;
      this.originalScore = 0;
      this.currentContent = '';
      this.currentProjectIndex = -1;
    },

    calculateTotalScore() {
      // 更新当前类型的分数
      this.reviewForm[this.scoreType === 'bg' ? 'bgScore' :
          this.scoreType === 'innovation' ? 'innovationScore' : 'economicScore'] = this.currentScore;

      // 计算总分 - 只有三个得分都有值时才计算
      if (this.reviewForm.bgScore !== null && this.reviewForm.bgScore !== '' &&
          this.reviewForm.innovationScore !== null && this.reviewForm.innovationScore !== '' &&
          this.reviewForm.economicScore !== null && this.reviewForm.economicScore !== '') {
        this.reviewForm.totalScore = (
            this.reviewForm.bgScore +
            this.reviewForm.innovationScore +
            this.reviewForm.economicScore
        ).toFixed(1);
      } else {
        this.reviewForm.totalScore = '-';
      }
    },

    // 新增：关闭并保存当前评分
    async handleCloseAndSave() {
      const saveSuccess = await this.saveCurrentScore();
      if (saveSuccess) {
        this.$message.success('评分已保存');
        // 关闭抽屉
        this.closeScoreDrawer();
        // 刷新表格数据
        await this.fetchProjectList();
      }
    },

    // 处理保存当前评分的方法（保留原方法，供其他地方调用）
    async handleSaveCurrentScore() {
      const saveSuccess = await this.saveCurrentScore();
      if (saveSuccess) {
        this.$message.success('评分已保存');
        // 保存成功后更新原始分数，避免关闭时再次提示
        this.originalScore = this.currentScore;
        // 重新获取项目数据刷新显示
        await this.fetchProjectList();
      }
    },

    // 保存当前评分
    async saveCurrentScore() {
      // 验证currentProject
      if (!this.currentProject || !this.currentProject.awardId) {
        this.$message.error('项目信息不存在，无法保存');
        return false;
      }

      // 验证分数是否在有效范围内
      if (!this.canSaveCurrentScore) {
        this.$message.error(`请输入0到${this.scoreMax}之间的整数`);
        return false;
      }

      try {
        // 检查是否所有分数都已填写，决定状态是评审中(1)还是已评审(2)
        const allScoresCompleted =
            this.reviewForm.bgScore !== null && this.reviewForm.bgScore !== '' &&
            this.reviewForm.innovationScore !== null && this.reviewForm.innovationScore !== '' &&
            this.reviewForm.economicScore !== null && this.reviewForm.economicScore !== '';

        const scoreData = {
          awardId: this.reviewForm.awardId,
          expertId: this.reviewForm.expertId,
          scoreRemark: this.reviewForm.scoreRemark,
          scoreStatus: allScoresCompleted ? 2 : 1, // 全部完成则为已评审(2)，否则为评审中(1)
          // 只传递已填写的分数，未填写的不传递
          ...(this.reviewForm.bgScore !== null && this.reviewForm.bgScore !== '' && {bgScore: this.reviewForm.bgScore}),
          ...(this.reviewForm.innovationScore !== null && this.reviewForm.innovationScore !== '' && {innovationScore: this.reviewForm.innovationScore}),
          ...(this.reviewForm.economicScore !== null && this.reviewForm.economicScore !== '' && {economicScore: this.reviewForm.economicScore})
        };

        const response = await saveScore(scoreData);
        if (response.code === '200') {
          return true;
        } else {
          this.$message.error(response.message || '保存失败');
          return false;
        }
      } catch (error) {
        console.error('保存评分失败', error);
        this.$message.error('保存评分失败，请重试');
        return false;
      }
    },

    // 处理切换到下一个评分类型
    async handleGoToNext() {
      const nextType = this.getNextScoreType();
      if (nextType) {
        // 检查当前评分是否有值
        if (this.currentScore > 0) {
          // 有值则直接保存
          const saveSuccess = await this.saveCurrentScore();
          if (saveSuccess) {
            // 保存成功后刷新数据并切换
            this.switchToScoreType(nextType);
          }
        } else {
          // 没有值，直接切换但仍需刷新数据
          this.switchToScoreType(nextType);
        }
      }
    },

    // 处理切换到上一个评分类型
    async handleGoToPrevious() {
      const prevType = this.getPreviousScoreType();
      if (prevType) {
        // 检查当前评分是否有值
        if (this.currentScore > 0) {
          // 有值则直接保存
          const saveSuccess = await this.saveCurrentScore();
          if (saveSuccess) {
            // 保存成功后刷新数据并切换
            this.switchToScoreType(prevType);
          }
        } else {
          // 没有值，直接切换但仍需刷新数据
          this.switchToScoreType(prevType);
        }
      }
    },

    // 切换到指定的评分类型
    switchToScoreType(type) {
      const currentProjectId = this.currentProject.awardId;

      // 先刷新项目列表数据
      this.fetchProjectList().then(() => {
        // 数据刷新后再查找更新后的项目
        const updatedProject = this.filteredProjects.find(p => p.awardId === currentProjectId);
        if (updatedProject) {
          this.openScoreDrawer(updatedProject, type);
        } else {
          this.closeScoreDrawer();
          this.$message.error('项目数据已更新，无法继续操作');
        }
      });
    },

    // 获取下一个评分类型
    getNextScoreType() {
      switch (this.scoreType) {
        case 'bg':
          return 'innovation';
        case 'innovation':
          return 'economic';
        default:
          return '';
      }
    },

    // 获取上一个评分类型
    getPreviousScoreType() {
      switch (this.scoreType) {
        case 'innovation':
          return 'bg';
        case 'economic':
          return 'innovation';
        default:
          return '';
      }
    },

    // 获取评分类型的名称
    getScoreTypeName(type) {
      switch (type) {
        case 'bg':
          return '业务需求评分';
        case 'innovation':
          return '创造性评分';
        case 'economic':
          return '效益性评分';
        default:
          return '';
      }
    },

    // 处理抽屉关闭
    handleDrawerClose() {
      this.closeScoreDrawer();
    },

    // 抽屉关闭前的处理 - 询问是否保存
    async handleDrawerBeforeClose(done) {
      // 只有当分数有变化时才提示保存
      if (this.hasScoreChanged) {
        this.$confirm('当前评分尚未保存，是否保存后再关闭？', '提示', {
          confirmButtonText: '保存',
          cancelButtonText: '不保存',
          type: 'warning'
        }).then(async () => {
          // 用户选择保存
          const saveSuccess = await this.saveCurrentScore();
          if (saveSuccess) {
            // 保存成功后刷新表格数据
            await this.fetchProjectList();
            done();
          }
        }).catch(() => {
          // 用户选择不保存，直接关闭
          done();
        });
      } else {
        // 没有变化，直接关闭
        done();
      }
    },

    // 全部提交相关
    submitAllReviews() {
      if (this.canSubmitAll) {
        this.submitAllDialogVisible = true;
      }
    },

    async confirmSubmitAll() {
      this.submitLoading = true;
      try {
        const scoreList = this.filteredProjects.map(project => ({
          awardId: project.awardId,
          expertId: project.expertId,
          bgScore: project.bgScore,
          innovationScore: project.innovationScore,
          economicScore: project.economicScore,
          scoreRemark: project.scoreRemark || '',
          scoreStatus: 3 // 全部改为已提交状态(3)
        }));

        const response = await batchSaveScores(scoreList);
        if (response.code === '200') {
          // 1. 获取当前评委ID并更新状态
          const currentJudgeId = this.currentUser.id;
          if (currentJudgeId) {
            // 调用saveJudge接口更新状态码为2
            await saveJudge({
              id: currentJudgeId,
              codeStatus: 2 // 设置状态码为2
            });
          } else {
            console.warn('未获取到评委ID，无法更新状态');
          }

          // 2. 登出
          this.clearLoginInfo();
          this.redirectToLogin();

        } else {
          this.$message.error(response.message || '批量提交失败');
        }
      } catch (error) {
        console.error('批量提交失败', error);
        this.$message.error('批量提交失败，请重试');
      } finally {
        this.submitLoading = false;
      }
    }
  }
};
</script>

<style scoped>
.review-system-container {
  font-family: 'Helvetica Neue', Arial, sans-serif;
  background-color: #f5f7fa;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 页脚样式 */
.review-footer {
  margin-top: auto;
  padding: 20px 0;
  color: #8392a5;
  font-size: 16px;
  text-align: center;
  background-color: #fff;
  border-top: 1px solid #e8e8e8;
}

.review-footer p {
  margin: 5px 0;
}

/* 评审时间显示样式 */
.review-time-info {
  color: white;
  font-size: 1rem;
  padding: 5px 12px;
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
  gap: 5px;
}

.time-text {
  white-space: nowrap;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .review-time-info {
    margin-right: 0;
    margin-bottom: 8px;
  }

  .user-info-container {
    flex-wrap: wrap;
    justify-content: flex-end;
  }
}

/* 公告弹窗样式 */
.announcement-content {
  padding: 10px 0;
}

.announcement-content p,
.announcement-content li {
  font-size: 16px;
  line-height: 1.8;
}

.announcement-list {
  padding-left: 0;
  margin: 0;
  list-style: none;
}

.announcement-list li {
  margin-bottom: 12px;
  line-height: 1.8;
  display: flex;
  align-items: flex-start;
}

.announcement-list li i {
  color: #1890ff;
  margin-right: 8px;
  margin-top: 4px;
  flex-shrink: 0;
}

/* 顶部导航 */
.top-nav {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #1890ff;
  color: white;
  padding: 0 20px;
  height: 70px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logo-title h1 {
  font-size: 1.7rem;
  margin: 0;
  font-weight: 600;
}

.user-info-container {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.user-info {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 10px;
  border-radius: 4px;
  transition: background-color 0.2s;
  color: white;
  font-size: 1rem;
}

.user-info:hover {
  background-color: rgba(255, 255, 255, 0.1);
}

.user-info .el-icon-user-circle {
  font-size: 1.4rem;
  margin-right: 8px;
  color: white;
}

.username {
  margin-right: 8px;
  color: white;
}

.specialty-tag {
  background-color: rgba(255, 255, 255, 0.2);
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.9rem;
  margin-right: 8px;
  color: white;
}

.user-info .el-icon-arrow-down {
  color: white;
}

/* 筛选和排序栏 */
.filter-sort-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: white;
  border-bottom: 1px solid #e8e8e8;
  flex-wrap: wrap;
  gap: 10px;
  font-size: 16px;
}

.filter-group {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.sort-group {
  display: flex;
  align-items: center;
}

/* 评审进度 */
.review-progress {
  display: flex;
  align-items: center;
  padding: 15px 20px;
  background-color: white;
  border-bottom: 1px solid #e8e8e8;
  font-size: 16px;
}

.progress-info {
  display: flex;
  align-items: center;
  margin-right: 15px;
  white-space: nowrap;
}

.completed-count {
  color: #1890ff;
  font-weight: bold;
  margin: 0 3px;
  font-size: 17px;
}

.total-count {
  font-weight: bold;
  margin: 0 3px;
  font-size: 17px;
}

/* 项目列表 */
.project-list-container {
  padding: 20px;
  flex: 1;
}

.el-table th,
.el-table td {
  font-size: 16px;
  padding: 12px 0;
}

.reviewed-score {
  color: #52c41a;
  font-weight: bold;
  font-size: 16px;
}

.unreviewed-score {
  color: #86909c;
  font-size: 16px;
}

.empty-state {
  padding: 40px 0;
  text-align: center;
  background-color: white;
  border-radius: 4px;
}

/* 评分单元格样式 */
.score-cell {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 5px 0;
}

.disabled-score {
  cursor: not-allowed;
  opacity: 0.7;
}

.score-edit-icon {
  margin-left: 5px;
  color: #1890ff;
  font-size: 16px;
  opacity: 0.7;
  transition: opacity 0.2s;
}

.score-cell:hover .score-edit-icon {
  opacity: 1;
}

.disabled-score:hover .score-edit-icon {
  opacity: 0.5;
}

.score-form {
  margin-top: 10px;
}

/* 抽屉底部按钮样式 - 改为靠右显示 */
.drawer-footer {
  padding: 15px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
}

.button-group {
  display: flex;
  gap: 10px;
  align-items: center;
}

/* 按钮样式 */
.prev-btn, .next-btn, .close-btn {
  font-size: 16px;
  padding: 10px 20px;
}

.prev-btn i {
  margin-right: 5px;
}

.next-btn i {
  margin-left: 5px;
}

/* 关闭按钮样式 */
.close-btn {
  margin: 0 5px;
}

/* 内容展示样式 */
.collapsible-content {
  position: relative;
}

.preformatted-text {
  white-space: pre-wrap;
  word-wrap: break-word;
  line-height: 1.8;
  margin: 0;
  color: #4e5969;
  font-size: 16px;
}

.toggle-button {
  text-align: center;
  padding: 8px 0;
  color: #1890ff;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.toggle-button i {
  margin-left: 5px;
  font-size: 14px;
}

.criteria-toggle {
  padding: 12px 0;
  border-bottom: 1px solid #e8e8e8;
  margin-bottom: 10px;
}

/* 评分标准样式 */
.criteria-table-wrapper {
  overflow-x: auto;
}

.criteria-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 16px;
}

.criteria-table th,
.criteria-table td {
  border: 1px solid #e8e8e8;
  padding: 12px 15px;
  text-align: left;
}

.criteria-table th {
  background-color: #e6f7ff;
  color: #1890ff;
  font-weight: 500;
  white-space: nowrap;
}

.criteria-table tr:nth-child(even) {
  background-color: #f9f9f9;
}

/* 数字输入框样式 */
.score-input {
  width: 100%;
  margin-bottom: 10px;
}

.el-input-number {
  font-size: 16px;
}

.el-tag {
  font-size: 16px;
}

/* 全部提交确认弹窗 */
.submit-confirm-content {
  margin-bottom: 15px;
}

.submit-confirm-content p {
  font-size: 16px;
  line-height: 1.8;
}

.review-summary {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
  padding-top: 15px;
  border-top: 1px dashed #e8e8e8;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
}

.summary-item span {
  font-size: 16px;
}

.summary-value {
  font-size: 1.2rem;
  font-weight: bold;
  color: #1890ff;
  margin-top: 5px;
}

/* 表格行样式 */
.submitted-row {
  background-color: #f6ffed !important;
}

.reviewed-row {
  background-color: #e6f7ff !important;
}

.inreview-row {
  background-color: #fff7e6 !important;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .filter-sort-bar {
    flex-direction: column;
    align-items: flex-start;
  }

  .sort-group {
    width: 100%;
    margin-top: 10px;
  }

  .criteria-table th,
  .criteria-table td {
    padding: 8px 10px;
    font-size: 15px;
  }

  .announcement-list li {
    flex-direction: column;
  }

  .announcement-list li i {
    margin-bottom: 5px;
  }

  /* 抽屉按钮响应式样式 */
  .button-group {
    flex-wrap: wrap;
    justify-content: center;
    width: 100%;
  }

  .prev-btn, .next-btn, .close-btn {
    flex: 1;
    min-width: 120px;
    margin-bottom: 5px;
  }
}
</style>
